<?php
/**
 * WorkController
 * 
 * @package uustudio
 * @author 大眼仔~旭
 * @copyright 2013
 * @version $Id$
 * @access public
 */
class WorkController extends Controller
{
	
	function init(){
		if(isset($_POST['SESSION_ID'])){
			$session=Yii::app()->getSession();
			$session->close();
			$session->sessionID = $_POST['SESSION_ID'];
			$session->open();
		}
	}
	
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/work';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','list','details','listpage','albumpage'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','upload','checkupload','setfolder'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		
//		$model = $this->loadModel($id);			
		
		$model = Media::model()->findByPk((int)$id);
		
    	$this->meta['Description'] = $model->media_describe;
		$this->meta['KeyWords'] = $model->media_name;
		
		$this->setMetaInfo();		

      	$criteria = new CDbCriteria(array(
      		'condition'=>'file_status = :file_status AND file_pid = :file_pid',
      		'order'=>'file_id DESC',
      		'params'=>array(
      			':file_status'=>File::FILE_STATUS_PUBLISHED,
      			':file_pid'=>$id
      		)
      	));
      	
     	$count=File::model()->count($criteria);
     	$pages=new CPagination($count);
 
      	// results per page
     	$pages->pageSize=9;
     	$pages->applyLimit($criteria);
    	$dataProvider = File::model()->findAll($criteria);    	
    	
    	
    	//自动增加点击量
    	//		echo $_GET['id'];

    	//		$model->save();
    	$key = Yii::app()->user->getStateKeyPrefix().Yii::app()->request->getUserHostAddress().Yii::app()->user->name.$model->category->cate_id.$model->media_id;
//     	echo $key;
    	$key = md5($key);
    	$session = Yii::app()->session;
    	if(!isset($session[$key])){
    	
    		Visitors::model()->addMediaVisitorInfo($model->media_id);
    		
//     		if($model->save()){
    			$session[$key] = md5(time());
    			//$this->redirect(index);
//     		}
    		//			else{
    		//				die("数据更新失败");
    		//			}
    		
    	}
    	
    	
    	
//    	$visitors = Visitors::model()->getMediaVisitors($id);
 
      	$this->render('view',array(
			'dataProvider' => $dataProvider,
			'pages' => $pages,
      		'model' => $model,
//      		'visitors' => $visitors
		));
		
	}
	
	/**
	 * 上传相片
	 */
	public function actionUpload()
	{
	
		
		if(Yii::app()->user->isGuest) throw new CHttpException(403,'bad');
	

		if (!empty($_FILES)) {
			
			//使用uploadify组件s
			UtilUploader::uploadify('Filedata');

		}
		
		$this->render('upload', array()	);
	
	}
	
	public function actionCheckUpload()
	{
        UtilUploader::uploadifyCheck();
	}
	
	public function actionSetFolder($id)
	{
		$result = array();
		
		$model = $this->loadModel($id);
		
		$model->media_pic_id = intval($_GET['fid']);
		
		if ($model->save())
		{
			$result['state'] =  'success';
            $result['thumb'] = addslashes(File::model()->generateFilePath(File::model()->findByPk($_GET['fid']),false,true));
		}
		else
		{
			$result['state'] = 'fail';
		}
		
		echo json_encode($result);
			
		
	}


	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Media;

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		if(isset($_POST['Media']))
		{
			$model->attributes=$_POST['Media'];
			
// 			UtilHelper::dump($model->attributes);
			
// 			die();
			
			if($model->save())
				$this->redirect(array('upload','id'=>$model->media_id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		if(isset($_POST['Media']))
		{
			$model->attributes=$_POST['Media'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->media_id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$this->meta['Description'] = '在此处收录了与我相关的相册，独立开发的Web应用系统，还有一些Yii框架的扩展';
		$this->meta['KeyWords'] = '作品展示';
		
		$this->setMetaInfo();	
		
		//以下作出修改2011.11.26
		
// 		$criteria = new CDbCriteria(array(
// 			'condition' => 'media_cid = :media_cid AND media_status = :media_status',
// 			'params' => array(
// 				':media_cid' => $id,
// 				':media_status' => Media::STATUS_PUBLISHED
// 			)
// 		));
		
// 		$criteria = new CDbCriteria(array( 
// 				'condition' => 'media_status = :media_status',
// 				'params' => array(
// 						':media_status' => Media::STATUS_PUBLISHED
// 				)
// 		));
		
// 		$dataProvider=new CActiveDataProvider('Media',array(
// 			'criteria' => $criteria
// 		));

		$dataProvider = Media::model()->findAll(array(
				'condition'=>'media_status = :media_status',
//				'limit'=>5,
				'order'=>'media_id DESC',
				'params'=>array(
						':media_status'=>Media::STATUS_PUBLISHED
				)
		));
		
		
// 		UtilTools::dumpObject($dataProvider, true);
		
// 		Yii::app()->end();

		//2013/4/29更改
		$model = Category::model()->find(array(
				'condition'=>'cate_type = :cate_type AND cate_pid = :cate_pid',
				'order'=>'cate_id DESC',
				'limit'=>5,
				'params'=>array(
						':cate_type' => Category::CATEGORY_MEDIA,
						':cate_pid' => 0,
				)
		));
		
		$this->render('index',array(
 				'dataProvider'=>$dataProvider,
				'model'=>$model
		));
	}
	
	public function actionListPage()
	{
		$start = microtime(true);
		
		$id = $_GET['id'];
		$num = $_GET["num"]?$_GET['num']:10;
		$page = $_GET["page"]?$_GET['page']:1;
		
//		UtilHelper::dump($_GET);
				
		$data = array();
		$i=0;
		$pageSize = 10;
        
        $cacheId = md5(Yii::app()->request->getUrl().'_'.$id.'_'.$page);
        
       $data = Yii::app()->fileCache->get($cacheId);
       
       if($data === false)
       {
		
           $data = Media::model()->getPictureList($id, $page, $pageSize);

           
           $dependency = new CDbCacheDependency('SELECT MAX("media_id") FROM {{media}}');
           
           Yii::app()->fileCache->set($cacheId,$data, 86400*7,$dependency);
   
       }
        
//          $data = Media::model()->getPictureList($id, $page, $pageSize);

       $end = microtime(true);

       UtilHelper::actionAnalysize($this, $start, $end);
       
        $display = $data;
        
        
        $display['POST'] = $_POST;
        $display['GET'] = $_GET;


        
        UtilHelper::writeToFile($display);
        

		echo json_encode($data);
	}
	
	
	public function actionAlbumPage()
	{
		$num = $_GET["num"]?$_GET['num']:10;
		$page = $_GET["page"]?$_GET['page']:1;
        
 	
		//		UtilHelper::dump($_GET);
	
		$data = array();
		$i=0;
		$pageSize = 10;
        
        $cacheId = md5(Yii::app()->request->getUrl().$page);
        
        

        
        $data = Yii::app()->fileCache->get($cacheId);
        

       if($data ===false)
       {    
           
           $data = Media::model()->getMediaListInfo($page, $pageSize);

      
           $dependency = new CDbCacheDependency('SELECT MAX(media_id) FROM {{media}}');
           
           //$dependency = new CFileCacheDependency('./public/log.txt');
      
           Yii::app()->fileCache->set($cacheId, $data, 86400*7, $dependency);
      
      }

       
//        $data = Media::model()->getMediaListInfo($page, $pageSize);
       
//       UtilHelper::dump($data);
//       
//       die();

        $display = $data;

        $display['POST'] = $_POST;
        $display['GET'] = $_GET;
        
        UtilHelper::writeToFile($display);
	
		echo json_encode($data);
	}
	
	public function actionList($id) 
	{
	
		//$album = $this->loadModel($id);
		
		$model = Category::model()->findByPk($id);//($album->media_cid);
		
		$this->meta['Description'] = $model->cate_des;
		$this->meta['KeyWords'] = $model->cate_name;
		
		$this->setMetaInfo();	
		
		$criteria = new CDbCriteria(array(
			'condition' => 'media_cid = :media_cid AND media_status = :media_status',
			'params' => array(
				':media_cid' => $id,
				':media_status' => Media::STATUS_PUBLISHED
			)
		));
		
		$dataProvider=new CActiveDataProvider('Media',array(
			'criteria' => $criteria
		));
		
		$this->render('list',array(
			'dataProvider'=>$dataProvider,
			'model'=>$model
		));		
	}
	
	public function actionDetails()
	{
		if(!isset($_GET['id']))
			throw new CHttpException(404,'The requested page doesn\'t exist.');
			
		
		$id = $_GET['id'];
      	$criteria = new CDbCriteria(array(
      		'condition'=>'file_pid = '.$id
      	));
     	$count=File::model()->count($criteria);
     	$pages=new CPagination($count);
 
      	// results per page
     	$pages->pageSize=9;
     	$pages->applyLimit($criteria);
    	$dataProvider = File::model()->findAll($criteria);
    	
    	$model = $this->loadModel($id);
 
      	$this->render('list',array(
			'dataProvider' => $dataProvider,
			'pages' => $pages,
      		'model' => $model
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Media('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Media']))
			$model->attributes=$_GET['Media'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Media::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='Media-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
